package com.longcai.service.impl.nearby;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longcai.bean.ApiResult;
import com.longcai.bean.PageHelper;
import com.longcai.entity.customer.ClyjUser;
import com.longcai.entity.customer.ClyjUserAgent;
import com.longcai.entity.homepage.GoodsClass;
import com.longcai.entity.nearby.ClyjNearbyShops;
import com.longcai.feign.client.TraFeignClient;
import com.longcai.mapper.clyjuser.ClyjUserAgentMapper;
import com.longcai.mapper.clyjuser.ClyjUserMapper;
import com.longcai.mapper.goods.GoodsClassMapper;
import com.longcai.mapper.nearby.ClyjNearbyShopsMapper;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.nearby.ClyjNearbyShopsService;
import com.longcai.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 附近商铺 服务实现类
 * </p>
 *
 * @author ZZN
 * @since 2019-04-11
 */
@Service
public class ClyjNearbyShopsServiceImpl extends ServiceImpl<ClyjNearbyShopsMapper, ClyjNearbyShops> implements ClyjNearbyShopsService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ClyjNearbyShopsMapper clyjNearbyShopsMapper;
    @Autowired
    private GoodsClassMapper goodsClassMapper;
    @Autowired
    private ClyjUserMapper clyjUserMapper;
    @Autowired
    private TraFeignClient traFeignClient;
    @Autowired
    private ClyjUserAgentMapper clyjUserAgentMapper;

    /**
     * 获取店铺信息
     *
     * @param clyjNearbyShops
     * @return
     */
    @Override
    public PageTableResponse shopsList(ClyjNearbyShops clyjNearbyShops, PageHelper pageHelper) {
        try {
            //分页
            Page<ClyjNearbyShops> page = new Page<ClyjNearbyShops>(pageHelper.getStart(), pageHelper.getLength());
            //查询店铺
            QueryWrapper<ClyjNearbyShops> queryWrapper = new QueryWrapper<>();
            //查询登录用户角色
            LoginUser loginUser = UserUtil.getLoginUser();
            //查询是否为代理
            QueryWrapper<ClyjUserAgent> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("phone", loginUser.getPhone());
            ClyjUserAgent clyjUserAgent = this.clyjUserAgentMapper.selectOne(queryWrapper1);
            if (clyjUserAgent != null) {
               queryWrapper.like("shops_address",clyjUserAgent.getS_city()).or().like("shops_address",clyjUserAgent.getS_county());
            }

            if (!StringUtils.isEmpty(clyjNearbyShops.getShopsName()) && !clyjNearbyShops.getShopsName().equals("")) {
                queryWrapper.like("shops_name", clyjNearbyShops.getShopsName());
            }
            if (!StringUtils.isEmpty(clyjNearbyShops.getShopsFlag()) && !clyjNearbyShops.getShopsFlag().equals("")) {
                queryWrapper.like("shops_flag", clyjNearbyShops.getShopsFlag());
            }
            if (!StringUtils.isEmpty(clyjNearbyShops.getPhone()) && !clyjNearbyShops.getPhone().equals("")) {
                queryWrapper.like("phone", clyjNearbyShops.getPhone());
            }
            if (!StringUtils.isEmpty(clyjNearbyShops.getShopsType()) && !clyjNearbyShops.getShopsType().equals("")) {
                queryWrapper.like("shops_type", clyjNearbyShops.getShopsType());
            }
            if (!StringUtils.isEmpty(clyjNearbyShops.getShopCity()) && !clyjNearbyShops.getShopCity().equals("地级市")) {
                queryWrapper.like("shop_city", clyjNearbyShops.getShopCity());
            }
            if (!StringUtils.isEmpty(clyjNearbyShops.getShopCountry()) && !clyjNearbyShops.getShopCountry().equals("区、县级市")) {
                queryWrapper.like("shop_country", clyjNearbyShops.getShopCountry());
            }
            if (!StringUtils.isEmpty(clyjNearbyShops.getBegintime()) && !StringUtils.isEmpty(clyjNearbyShops.getEndt())) {
                queryWrapper.between("create_time", clyjNearbyShops.getBegintime(), clyjNearbyShops.getEndt());
            }
            queryWrapper.eq("status", "0");
            if (!StringUtils.isEmpty(clyjNearbyShops.getTypes()) && clyjNearbyShops.getTypes().equals("1")) {
                queryWrapper.eq("flag", 0);
            }
            //queryWrapper.eq("mich_id", loginUser.getUserId());
            IPage<ClyjNearbyShops> clyjNearbyShopsIPage = this.clyjNearbyShopsMapper.selectPage(page, queryWrapper);
            List<ClyjNearbyShops> clyjNearbyShopsList = clyjNearbyShopsIPage.getRecords();
            List list = new ArrayList();
            for (ClyjNearbyShops clyjNearbyShops1 : clyjNearbyShopsList) {
                GoodsClass goodsClass = this.goodsClassMapper.selectById(clyjNearbyShops1.getShopsType());
                clyjNearbyShops1.setShopsType(goodsClass.getName());
            }
            logger.debug("查询成功");

            PageTableResponse pageTableResponse = new PageTableResponse(clyjNearbyShopsIPage.getTotal(),
                    clyjNearbyShopsIPage.getTotal(), clyjNearbyShopsIPage.getRecords());
            return pageTableResponse;
        } catch (Exception e) {
            logger.error("查询失败");
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 根据Id获取店铺信息
     *
     * @param id
     * @return
     */
    @Override
    public ApiResult getById(String id) {
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("shops_id", id);
            ClyjNearbyShops clyjNearbyShops = this.clyjNearbyShopsMapper.selectOne(queryWrapper);
            GoodsClass goodsClass = this.goodsClassMapper.selectById(clyjNearbyShops.getShopsType());
            clyjNearbyShops.setShopsType(goodsClass.getName());
            logger.debug("查询成功", clyjNearbyShops);
            return ApiResult.success(clyjNearbyShops);
        } catch (Exception e) {
            logger.error("查询失败");
            e.printStackTrace();
            return ApiResult.fail("查询失败" + e.getMessage());
        }
    }

    /**
     * 店铺上线
     *
     * @param id
     */
    @Override
    public ApiResult upShop(String id) {
        try {
            QueryWrapper<ClyjNearbyShops> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("shops_id", id);
            ClyjNearbyShops clyjNearbyShops = this.clyjNearbyShopsMapper.selectOne(queryWrapper);
            clyjNearbyShops.setShopsFlag(0);
            Integer integer = clyjNearbyShopsMapper.updateById(clyjNearbyShops);
            logger.debug("修改成功");
            return ApiResult.success(integer);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改失败");
            return ApiResult.fail(e.getMessage());
        }

    }

    /**
     * 店铺下线
     *
     * @param id
     */
    @Override
    public ApiResult downShop(String id) {
        try {
            QueryWrapper<ClyjNearbyShops> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("shops_id", id);
            ClyjNearbyShops clyjNearbyShops = this.clyjNearbyShopsMapper.selectOne(queryWrapper);
            clyjNearbyShops.setShopsFlag(99);
            Integer integer = clyjNearbyShopsMapper.updateById(clyjNearbyShops);
            logger.debug("修改成功");
            return ApiResult.success(integer);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改失败");
            return ApiResult.fail(e.getMessage());
        }
    }

    /**
     * 删除店铺
     *
     * @param id
     */
    @Override
    public void deleteShopsList(String id) {
        try {
            QueryWrapper<ClyjNearbyShops> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("shops_id", id);
            ClyjNearbyShops clyjNearbyShops = new ClyjNearbyShops();
            clyjNearbyShops.setStatus("1");
            clyjNearbyShopsMapper.update(clyjNearbyShops, queryWrapper);
        } catch (Exception e) {
            e.getMessage();
            e.printStackTrace();
        }

    }

    /**
     * 获取所有店铺名称
     *
     * @return
     */
    @Override
    public List<ClyjNearbyShops> getAllshops() {
        return clyjNearbyShopsMapper.getAllshops();
    }

    /**
     * 审核通过更改店铺信息
     *
     * @param clyjNearbyShops
     * @return
     */
    @Override
    public ApiResult saveShops(ClyjNearbyShops clyjNearbyShops) {
        try {
            //设置通过信息
            if (StringUtils.isEmpty(clyjNearbyShops.getReason())) {
                QueryWrapper<ClyjNearbyShops> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("shops_id", clyjNearbyShops.getShopsId());
                ClyjNearbyShops clyjNearbyShops1 = this.clyjNearbyShopsMapper.selectOne(queryWrapper);
                String s = listUtil.listToString(clyjNearbyShops.getTypeIds());
                clyjNearbyShops1.setFlag(1);
                clyjNearbyShops1.setShopsAttr(s);
                clyjNearbyShops1.setEndTime(clyjNearbyShops.getEndTime());
                clyjNearbyShops1.setInvNumber(clyjNearbyShops.getInvNumber());
                //校验店铺富有账号开通
                ApiResult<?> result = this.traFeignClient.AddCompanyRegister(clyjNearbyShops1);
                if ("fail".equals(result.getCode())) {
                    return ApiResult.fail(result.getMsg());
                }
                //生成个人二维码
                //存放路径
                // 用户主目录
                String realPath = System.getProperties().getProperty("user.home");
                //跳转地址
                String content = " http://clyj.gaojunjun.cn/from/login";
                //名称
                String name = "image.jpg";
                File file = QRCodeUtils.testEncode(realPath, content, name);
                if (file != null) {
                    //文档上传oss
                    try {
                        String pox = name.substring(name.lastIndexOf(".") + 1);
                        InputStream inputStream = new FileInputStream(file);
                        //InputStream inputStream = this.getClass().getResourceAsStream("/qrcode/file");
                        Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/USERCODE/");
                        clyjNearbyShops1.setCode(uploadByInputStream.get("path").toString());
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                Integer integer = this.clyjNearbyShopsMapper.updateById(clyjNearbyShops1);
                //更改用户表对应的信息
                QueryWrapper<ClyjUser> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("user_id", clyjNearbyShops1.getMichId());
                ClyjUser clyjUser = this.clyjUserMapper.selectOne(queryWrapper1);
                clyjUser.setIsmich("1");
                clyjUser.setInvNumber(clyjNearbyShops.getInvNumber());
                clyjUser.setEndTime(clyjNearbyShops.getEndTime());
                clyjUserMapper.updateById(clyjUser);
                logger.debug("审核成功");
                return ApiResult.success(integer);
            } else {
                QueryWrapper<ClyjNearbyShops> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("shops_id", clyjNearbyShops.getShopsId());
                ClyjNearbyShops clyjNearbyShops1 = this.clyjNearbyShopsMapper.selectOne(queryWrapper);
                clyjNearbyShops1.setFlag(2);
                clyjNearbyShops1.setReason(clyjNearbyShops.getReason());
                Integer integer = this.clyjNearbyShopsMapper.updateById(clyjNearbyShops1);
                logger.debug("审核不通过");
                return ApiResult.success(integer);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("审核失败");
            return ApiResult.fail(e.getMessage());
        }
    }

    /**
     * 修改店铺信息
     *
     * @param clyjNearbyShops
     * @return
     */
    @Override
    public ApiResult updateShopsList(ClyjNearbyShops clyjNearbyShops) {
        try {
            QueryWrapper<ClyjNearbyShops> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("shops_id", clyjNearbyShops.getShopsId());
            Integer integer = this.clyjNearbyShopsMapper.update(clyjNearbyShops, queryWrapper);
            logger.debug("修改成功");
            return ApiResult.success(integer);
        } catch (Exception e) {
            logger.error("修改失败");
            e.printStackTrace();
            return ApiResult.fail("修改失败" + e.getMessage());
        }
    }
}
